import React, { Component } from 'react'
import { connect } from 'dva'
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Card, List, Avatar, Button, message, Popconfirm } from 'antd';
import { Link } from 'react-router-dom';
import Editor from '../Articles/Editor';

@connect(state => {
    const { articles: { recent }} = state
    return { recent }
})
class Recent extends Component {

    state = {
        modalVisible: false,
        article_Id: 0
    }; 

    componentDidMount() {
        this.props.dispatch({
            type: 'articles/getRecent'
        })
        //console.log('state: ' + this.state.recent)
    }


    itemRender = item => {
        const { id, title, content } = item;
        return (
            <List.Item actions={[
                <Button type='primary' onClick={() => this.handleModalVisible(true, id)}>Edit</Button>, 
                <Popconfirm title="Are you sure delete this article?" onConfirm={() => this.confirmDel(id)} okText="Yes" cancelText="No">
                    <Button type='danger'>Delete</Button>
                </Popconfirm>
                
                ]} 
            >
                <List.Item.Meta
                    avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                    title={<Link to={`/articles/show/${id}`}>{title}</Link>}
                    description={content}
                />
            </List.Item>
        )
    }

    handleModalVisible = (flag, id) => {
        this.setState({
            modalVisible: !!flag,
            article_Id: id
        });
    };

    handleModalUnv = () => {
        
        this.setState({
            modalVisible: false,
        });

    };

    confirmDel = (id) => {
        this.props.dispatch({
            type: 'articles/deleteArticle',
            article_Id: id
        })
    }





    render() {
        //console.log()
        //console.log('Recent s props : ' + this.props)
        const { recent } = this.props
        const { modalVisible, article_Id } = this.state 

        const parentMethods = {
            handleModalUnv: this.handleModalUnv,
            handleModalVisible: this.handleModalVisible,
        };
        
        return (
                <PageHeaderLayout
                    title="Recent articles"
                >
                    <Card bordered={false}>
                        
                        <List
                            itemLayout="horizontal"
                            dataSource={recent}
                            renderItem={this.itemRender}
                        />
                    </Card>
                    <Editor {...parentMethods} modalVisible={modalVisible} article_Id={article_Id}  />
                </PageHeaderLayout>
        )
    }
}

export default Recent